package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
 @Reference
 private UserService userService;

 @RequestMapping("/getUsername")
 public Result getUsername() {
  log.debug("获取用户名!!");
  //获取安全框架上下文对象
  SecurityContext context = SecurityContextHolder.getContext();
  //获取认证对象
  Authentication authentication = context.getAuthentication();
  //获取 Principal 重要对象
  Object principal = authentication.getPrincipal();
  if (principal instanceof User) {
   User user = (User) principal;
   String username = user.getUsername();
   return new Result(true, MessageConst.GET_USERNAME_SUCCESS, username);
  }
  return new Result(false, MessageConst.GET_USERNAME_FAIL);
 }

 @RequestMapping("/loginSuccess")
 public ModelAndView loginSuccess() {
  return new ModelAndView("redirect:http://oms.web.health:83/pages/main.html");
 }


 @RequestMapping("/loginError")
 public ModelAndView doError() {
  return new ModelAndView("redirect:http://oms.web.health:83/login.html");
 }

 //	@RequestMapping("/login")
//	public Result login(String username, String password){
//		log.debug("oms backend,user:"+username+" ,password:"+password);
//		if(userService.login(username,password)){
//			log.debug("login ok!!!");
//			return new Result(true, MessageConst.ACTION_SUCCESS);
//		}else{
//			log.debug("login fail");
//			return new Result(false,MessageConst.ACTION_FAIL);
//		}
//	}
 //用户新增
 @RequestMapping("/add")
 public Result add(@RequestBody SysUser user, Integer[] roleIds) {
  user.setStation("0");
  log.debug("UserController-add: User{ " + user + " }");
  log.debug("UserController-add: roleIds{ " + Arrays.toString(roleIds) + " }");
  //为新建的用户设置加密
  //默认的加密工具类
  PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
  //PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  // 加密调用的方法是 encode
  String encode = passwordEncoder.encode(user.getPassword());
  user.setPassword(encode);
  log.debug("用户加密后的密文：" + encode);
  userService.add(user, roleIds);
  log.debug(MessageConst.ADD_USER_SUCCESS);
  return new Result(true, MessageConst.ADD_USER_SUCCESS);
 }

 //分页查询用户信息展示
 @RequestMapping("/findPage")
 public PageResult findPage(@RequestBody QueryPageBean pageBean) {
  log.debug("UserController-findPage: QueryPageBean{ " + pageBean + " }");
  PageResult pageResult = userService.findPage(pageBean);
  log.debug("UserController-findPage: PageResult {" + pageResult + " }");
  return pageResult;
 }

 //根据userId查询用户信息
 @RequestMapping("/findById")
 public Result findById(Integer id){
  log.debug("UserController-findById: id{ " + id + " }");
  SysUser sysUser = userService.findById(id);
  log.debug("UserController-findById: SysUser{ " + sysUser + " }");
  return new Result(true, MessageConst.QUERY_USER_SUCCESS,sysUser);
 }
 //根据userId查询roleIds，用于修改时候查看哪些roleId被选中了 findRoleIdsByUserId
 @RequestMapping("/findRoleIdsByUserId")
 public Result findRoleIdsByUserId(Integer userId){
  log.debug("UserController-findRoleIdsByUserId: userId: { " + userId + " }");
  List<Integer> list = userService.findRoleIdsByUserId(userId);
  log.debug("roleIdList: { " + list + " }");
  return new Result(true,MessageConst.QUERY_ROLE_SUCCESS,list);
 }
 //修改user信息
 @RequestMapping("/edit")
 public Result edit(@RequestBody SysUser sysUser, Integer[] roleIds){
  //默认的加密工具类,如果修改了密码需要加密
  if (sysUser.getPassword()!=null&&sysUser.getPassword().length()>0){
   PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
   //PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
   // 加密调用的方法是 encode
   String encode = passwordEncoder.encode(sysUser.getPassword());
   sysUser.setPassword(encode);
  }else {//查询存在的密码，不修改密码
   SysUser userPWD = userService.findById(sysUser.getId());
   sysUser.setPassword(userPWD.getPassword());
  }
  log.debug("UserController-edit: User{ " + sysUser + " }");
  log.debug("UserController-edit: roleIds{ " + Arrays.toString(roleIds) + " }");
  userService.edit(sysUser,roleIds);
  log.debug(MessageConst.EDIT_USER_SUCCESS);
  return new Result(true, MessageConst.EDIT_USER_SUCCESS);
 }
 //根据id删除user信息
 @RequestMapping("/delById")
 public Result delById(Integer id){
  log.debug("delById : { " + id +"}" );
  userService.delById(id);
  log.debug(MessageConst.DELETE_USER_SUCCESS);
  return new Result(true,MessageConst.DELETE_USER_SUCCESS);
 }
}